package com.dwin.h5.app.ui.fragments;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.dwin.h5.app.R;
import com.dwin.h5.app.models.UserBean;
import com.dwin.h5.app.ui.BaseActivity;
import com.dwin.h5.app.ui.LoadingActivity;
import com.dwin.h5.app.utils.Constants;
import com.dwin.h5.app.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

public class BaseFragment extends Fragment {
    protected Context mContext;
    public static final String ACTION_HTTP = "httpCallback";
    public static final String ACTION_MQTT = "mqttCallback";
    protected UserBean mUser;

    protected SharedPreferences logMessage = null; //用户日志保存
    protected String language ="";
//    protected X5WebView mWebView;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = getActivity();
        logMessage = mContext.getSharedPreferences("logmessage", mContext.MODE_PRIVATE);
        language = logMessage.getString("language", "");
        Log.d("0508", "lang: " + language);
    }

    // h5语言切换，系统重启
    protected static void reStart(Context context) {
        Intent intent = new Intent(context, LoadingActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.fontScale != 1) {
            //非默认值
            ((BaseActivity) getActivity()).getResources();
        }
        super.onConfigurationChanged(newConfig);
    }

    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    protected String getVersionName() {
        String version = null;
        try {
            PackageManager manager = mContext.getPackageManager();
            PackageInfo info = manager.getPackageInfo(getActivity().getPackageName(), 0);
            version = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 权限检查方法
     *
     * @param permissions 权限数组
     * @return
     */
    public boolean hasPermission(String... permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    public void doCallPhonePermission() {
    }

    // 获得拍照，存储空间的访问权限
    public void doCameraPermission() {
    }

    // 父类提供默认的权限处理方法
    public void doSDCardPermission() {
    }

    public void doCoarseLocation() {
    }

    /**
     * 提供权限请求方法
     *
     * @param code
     * @param permissions
     */
    public void requestPermissions(int code, String... permissions) {
        ActivityCompat.requestPermissions(getActivity(), permissions, code);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case Constants.WRITE_EXTERNAL_CODE:
                doSDCardPermission();
                break;
            case Constants.CAMERA_CODE:
                doCameraPermission();
                break;
            case Constants.COARSE_LOCATION_CODE:
                List<String> deniedList = new ArrayList<>(); // 遍历所有申请的权限，把被拒绝的权限放入集合
                for (int i = 0; i < grantResults.length; i++) {
                    int grantResult = grantResults[i];
                    if (grantResult == PackageManager.PERMISSION_GRANTED) {
//                       用户同意权限
                    } else {
                        deniedList.add(permissions[i]);
                    }
                }
                if (deniedList.isEmpty()) {
                    doCoarseLocation();
                } else {
                    ToastUtil.toastShort(mContext, R.string.go_setting_open_location_permission);
                }
                break;

            case Constants.CALL_PHONE: // 拨打电话权限
                doCallPhonePermission();
                break;
            default:
                break;
        }
    }



    public static String replaceLast(String string, String match, String replace) {
        if (null == replace) {
            //参数不合法，原样返回
            return string;
        }
        StringBuilder sBuilder = new StringBuilder(string);
        int lastIndexOf = sBuilder.lastIndexOf(match);
        if (-1 == lastIndexOf) {
            return string;
        }
        return sBuilder.replace(lastIndexOf, lastIndexOf + match.length(), replace).toString();
    }

    /**
     * 信息太长,分段打印
     *
     * @param tag
     * @param msg
     */
    protected void logDebug(String tag, String msg) {
        //因为String的length是字符数量不是字节数量所以为了防止中文字符过多，
        //  把4*1024的MAX字节打印长度改为2001字符数
        int max_str_length = 2001 - tag.length();
        //大于4000时
        while (msg.length() > max_str_length) {
            Log.i(tag, msg.substring(0, max_str_length));
            msg = msg.substring(max_str_length);
        }
        //剩余部分
        Log.i(tag, msg);
    }

    protected static String[] listToArray(List<String> list) {
        String[] array = {};
        if (list == null || list.size() == 0) {
            return null;
        } else {
            array = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                array[i] = list.get(i);
            }
        }
        return array;
    }

}
